package com.warrior.service;

import com.warrior.Exception.ProjectException;
import com.warrior.entity.*;
import com.warrior.respository.*;
import com.warrior.util.CommonUtils;
import com.warrior.util.DateUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Shawn on 2017/3/13.
 */
@Service
public class UserService {

    private static final Logger logger = LogManager.getLogger(UserService.class.getName());

    @Autowired
    private IUserRepository userRepository;

    @Autowired
    private ITicketTransformRepository ticketTransformRepository;

    @Autowired
    private ITicketRepository ticketRepository;

    @Autowired
    private TeamService teamService;

    @Autowired
    private IUserActivityRepository userActivityRepository;

    @Autowired
    private ActivityService activityService;


    /**
     * 添加/更新一个用户
     *
     * @param userEntity
     */
    @Transactional
    public void saveUser(UserEntity userEntity) {
        if (logger.isDebugEnabled()) {
            logger.debug("saveUser(UserEntity userEntity={}) - start", userEntity); //$NON-NLS-1$
        }

        this.userRepository.saveAndFlush(userEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("saveUser(UserEntity) - end"); //$NON-NLS-1$
        }
    }

    @Transactional
    public UserEntity findUserByToken(String token){
        UserEntity wxChatToken = this.userRepository.findUserEntityByWxChatToken(token);
        return wxChatToken;
    }


    /**
     * 用户买票
     *
     * @param userId
     * @param ticketId
     */
    @Transactional
    public void userBuyTicket(String userId, String ticketId) {
        if (logger.isDebugEnabled()) {
            logger.debug("userBuyTicket(String userId={}, String ticketId={}) - start", userId, ticketId); //$NON-NLS-1$
        }

        TicketTransformEntity ticketTransformEntity = new TicketTransformEntity();
        DateUtil dateUtil = new DateUtil();
        ticketTransformEntity.setCreatedAt(dateUtil.Date2Timestamp(new Date()));
        ticketTransformEntity.setUpdateAt(dateUtil.Date2Timestamp(new Date()));
        ticketTransformEntity.setCreatedBy("Shawn");
        ticketTransformEntity.setUpdateBy("admin");
        ticketTransformEntity.setUserId(userId);
        ticketTransformEntity.setTicketId(ticketId);
        this.ticketTransformRepository.save(ticketTransformEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("userBuyTicket(String, String) - end"); //$NON-NLS-1$
        }
    }

    /**
     * 根据用户id分页用户所拥有的票务信息,1表示正常,-1表示已过期
     *
     * @param userId
     * @param status
     * @return
     */
    @Transactional(readOnly = true)
    public List<TicketEntity> findAllTicketByUserId(String userId, int status) {
        if (logger.isDebugEnabled()) {
            logger.debug("findAllTicketByUserId(String userId={}, int status={}) - start", userId, status); //$NON-NLS-1$
        }
        List<TicketEntity> ticketEntities = new ArrayList<>();
        List<TicketTransformEntity> ticketByUserIdAndTicketStatus = ticketTransformRepository.findTicketByUserId(userId);
        for (int i = 0; i < ticketByUserIdAndTicketStatus.size(); i++) {
            String ticketId = ticketByUserIdAndTicketStatus.get(i).getTicketId();
            TicketEntity ticketEntityById = ticketRepository.findTicketEntityByIdAndTicketStatus(ticketId, status);
            if (null != ticketEntityById) {
                ticketEntities.add(ticketEntityById);
            }
        }

        if (logger.isDebugEnabled()) {
            logger.debug("findAllTicketByUserId(String, int) - end"); //$NON-NLS-1$
        }
        return ticketEntities;
    }

    /**
     * 根据id查找用户信息
     *
     * @param userId
     * @return
     */
    @Transactional(readOnly = true)
    public UserEntity findUserById(String userId) {
        if (logger.isDebugEnabled()) {
            logger.debug("findUserById(String userId={}) - start", userId); //$NON-NLS-1$
        }

        UserEntity returnUserEntity = this.userRepository.findUserEntityById(userId);
        if (logger.isDebugEnabled()) {
            logger.debug("findUserById(String) - end"); //$NON-NLS-1$
        }
        return returnUserEntity;
    }

    /**
     * @param userId   用户id
     * @param nickName 用户昵称
     * @throws ProjectException 空异常
     */
    @Transactional
    public void modifiedUserNickName(String userId, String nickName) throws ProjectException {
        if (logger.isDebugEnabled()) {
            logger.debug("modifiedUserNickName(String userId={}, String nickName={}) - start", userId, nickName); //$NON-NLS-1$
        }

        UserEntity userEntity = this.findUserById(userId);
        if (null != userEntity) {
            userEntity.setNickname(nickName);
            this.saveUser(userEntity);
        } else {
            throw new ProjectException("未找到该用户");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("modifiedUserNickName(String, String) - end"); //$NON-NLS-1$
        }
    }

    /**
     * @param userId  用户id
     * @param picPath 头像地址
     * @throws ProjectException 空异常
     */
    @Transactional
    public void modifiedUserPic(String userId, String picPath) throws ProjectException {
        if (logger.isDebugEnabled()) {
            logger.debug("modifiedUserPic(String userId={}, String picPath={}) - start", userId, picPath); //$NON-NLS-1$
        }

        UserEntity userEntity = this.findUserById(userId);
        if (null != userEntity) {
            userEntity.setUserLocalPicPath(picPath);
            this.saveUser(userEntity);
        } else {
            throw new ProjectException("未找到该用户");
        }

        if (logger.isDebugEnabled()) {
            logger.debug("modifiedUserPic(String, String) - end"); //$NON-NLS-1$
        }
    }

    /**
     * 根据队长找到所有队员信息
     *
     * @param captionId 队长id
     * @return
     */
    @Transactional
    public List<UserEntity> findTeamMember(String captionId) {
        if (logger.isDebugEnabled()) {
            logger.debug("findTeamMember(String captionId={}) - start", captionId); //$NON-NLS-1$
        }

        UserEntity userEntity = this.findUserById(captionId);
        TeamEntity teamEntity = userEntity.getTeamEntity();
        List<UserEntity> userEntities = null;
        if (null != teamEntity) {
            userEntities = this.userRepository.findUserByTeamEntity(teamEntity);
        }

        if (logger.isDebugEnabled()) {
            logger.debug("findTeamMember(String) - end"); //$NON-NLS-1$
        }
        return userEntities;
    }

    /**
     * @param teamId 队伍id
     * @param userId 用户id
     * @return
     */
    @Transactional
    public UserEntity addNewMemberToTeam(String teamId, String userId) {
        if (logger.isDebugEnabled()) {
            logger.debug("addNewMemberToTeam(String teamId={}, String userId={}) - start", teamId, userId); //$NON-NLS-1$
        }

        TeamEntity teamEntity = this.teamService.findTeamByTeamId(teamId);
        UserEntity userEntity = this.findUserById(userId);
        if (null == userEntity) {
            //如果用户没有注册,则拿微信授权,并增加一个用户


        } else {
            //已注册直接保存用户
            userEntity.setTeamEntity(teamEntity);
        }
        this.saveUser(userEntity);

        if (logger.isDebugEnabled()) {
            logger.debug("addNewMemberToTeam(String, String) - end"); //$NON-NLS-1$
        }
        return userEntity;
    }


    /**
     * 保存用户上传图片路径
     *
     * @param path   路径
     * @param userId 用户id
     */
    public void uploadIdCardPic(String path, String userId) {
        UserEntity userEntity = this.findUserById(userId);
        userEntity.setIdCardPicPath(path);
        this.saveUser(userEntity);
    }


    /**
     * 根据活动id查出所有用户
     *
     * @param activityId 活动id
     * @return List<UserActivityEntity>
     */
    public List<UserActivityEntity> findAllUserByActivityId(String activityId) {
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        int status = 2;
        List<UserActivityEntity> list = this.userActivityRepository.findAllUserEntityByActivityByActivityIdAndStatus(activityEntity, status);
        return list;
    }


    /**
     * 根据活动id查出所有用户
     *
     * @param activityId 活动id
     * @return List<UserActivityEntity>
     */
    public List<UserActivityEntity> findAllUserByActivityIdWithoutStatus(String activityId) {
        ActivityEntity activityEntity = this.activityService.findActivityById(activityId);
        List<UserActivityEntity> list = this.userActivityRepository.findAllUserEntityByActivityByActivityId(activityEntity);
        return list;
    }

    public void deleteUserActivity(String id){
        this.userActivityRepository.delete(id);
    }

    /**
     * 保存用户上传图片路径
     *
     * @param path   路径
     * @param userId 用户id
     */
    public void uploadPic(String path, String userId) {
        UserEntity userEntity = this.findUserById(userId);
        userEntity.setUserLocalPicPath(path);
        this.saveUser(userEntity);
    }


    public Page<UserEntity> findAllUsers(int size, int page, String orderType){

        Sort sort = new Sort(Sort.Direction.ASC, "createdAt");
        if ("desc".equals(orderType)) {
            sort = new Sort(Sort.Direction.DESC, "createdAt");
        }
        //设置分页参数
        Pageable pageable = new PageRequest(page, (size <= 0) ? 10 : size, sort);
        Page<UserEntity> userEntities = this.userRepository.findAll(pageable);
        return userEntities;
    }




}
